<template>
  <div class="page-content">
    <div class="header">
      <h3>报名地点</h3>
    </div>
    <!-- 表格菜单 -->
    <el-tabs v-model="tableLayout" class="demo-tabs" @tab-change="handleClick" style="margin-top: 20px">
      <el-tab-pane label="驾校管理" name="1"> </el-tab-pane>
      <el-tab-pane label="车型分类" name="2"> </el-tab-pane>
      <el-tab-pane label="报名地点" name="3"> </el-tab-pane>
      <el-tab-pane label="招生员" name="4"> </el-tab-pane>
      <el-tab-pane label="教练管理" name="5"> </el-tab-pane>
      <el-tab-pane label="训练场" name="6"> </el-tab-pane>
    </el-tabs>
    <!-- 表格菜单 -->
    <el-row style="margin-top: 20px">
      <div style="width: 12px"></div>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增报名地点</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <el-table-column label="排序" prop="sort" align="center" />
        <el-table-column label="报名地点" prop="name" align="center" />
        <el-table-column label="报名点照片" prop="photo" align="center">
          <template #default="scope">
            <img class="tableimg" :src="scope.row.photo" v-if="scope.row.photo" />
          </template>
        </el-table-column>
        <el-table-column label="联系人" prop="contactPerson" align="center" />
        <el-table-column label="联系电话" prop="contactPhone" align="center" />
        <el-table-column label="报名地址" prop="address" align="center" />
        <el-table-column #default="scope" label="线上展示" align="center">
          <el-switch v-model="scope.row.onlineStatus" @click="editOnlineStatus(scope.row.id, scope.row.onlineStatus)" />
        </el-table-column>
        <el-table-column #default="scope" label="启用状态" align="center">
          <el-switch v-model="scope.row.activeStatus" @click="editActiveStatus(scope.row.id, scope.row.activeStatus)" />
        </el-table-column>
        <el-table-column label=" 创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增报名点' : '编辑报名点'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="地点名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="联系人" prop="phonename">
          <el-input v-model="form.contactPerson" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.contactPhone" />
        </el-form-item>
        <el-form-item label="报名地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="地图定位">
          <el-row :gutter="12">
            <el-col :span="6"><el-button @click="showMapDialog = true">选择经纬度</el-button></el-col>
            <el-col :span="8"><el-input v-model="form.latitude"></el-input></el-col>
            <el-col :span="8"><el-input v-model="form.longitude"></el-input></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="报名点照片" prop="photo">
          <el-input v-model="form.photo" style="display: none"></el-input>
          <div class="avatar-uploader" @click="showImageChooseDialog = true">
            <el-image v-if="form.photo" :src="form.photo" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
            <div v-if="form.photo" class="mask">替换</div>
            <el-icon v-if="form.photo" class="del-image" :size="20" @click.stop="handleDelImg">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="线上展示" prop="onlineStatus">
          <el-switch v-model="form.onlineStatus" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="启用状态" prop="activeStatus">
          <el-switch v-model="form.activeStatus" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)" :loading="editLoading">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
      :operationType="false"></image-selected-dialog>

    <map-dialog v-if="showMapDialog" :show-map-dialog-visible="showMapDialog" @cancel="showMapDialog = false"
      @location-selected="selectMapAddress"></map-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getDriveSchoolList,
  AddDriveSchoolList,
  deleteDriveSchool,
  EditDriveSchoolList
} from '@/api/driverSchoolApi'
import { useUserStore } from '@/store/modules/user'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import MapDialog from '@/views/drivingschool/components/MapSelectorDialog.vue'

const userStore = useUserStore()
const dialogVisible = ref(false)
const permissionDialog = ref(false)
const tableLayout = ref('3')
const tableLoading = ref(false)
const showMapDialog = ref(false)

const formRef = ref<FormInstance>()
const router = useRouter() // 使用useRouter获取路由实例
const editLoading = ref(false)

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入报名名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '请输入正确排序', trigger: 'blur' }],
  photo: [{ required: true, message: '请上传图片', trigger: 'change' }],
})

const form = reactive({
  id: '',
  storeId: '',
  sort: '1',
  name: '',
  contactPerson: '',
  photo: '',
  contactPhone: '',
  address: '',
  onlineStatus: 1,
  activeStatus: 1,
  latitude: '',
  longitude: ''
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    form.photo = value.fileUrl
  }
  showImageChooseDialog.value = false
}

const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true

    const { code, data } = await getDriveSchoolList({
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    if (code === '00000') {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
const tableData = ref([])

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.photo = row.photo
    form.latitude = row.latitude
    form.longitude = row.longitude
  } else {
    form.id = ''
    form.sort = '1'
    form.name = ''
    form.contactPerson = ''
    form.photo = ''
    form.contactPhone = ''
    form.address = ''
    form.onlineStatus = 1
    form.activeStatus = 1
    form.latitude = ''
    form.longitude = ''
    form.photo = ''
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
  console.log(row.contactPerson, 'row===')
  Object.assign(form, {
    contactPerson: row.contactPerson,
    sort: row.sort,
    contactPhone: row.contactPhone,
    photo: row.photo,
    address: row.address,
    latitude: row.latitude,
    longitude: row.longitude,
    onlineStatus: row.onlineStatus == true ? 1 : 0,
    activeStatus: row.activeStatus == true ? 1 : 0
  })
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该报名点吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await deleteDriveSchool(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      // formEl.resetFields()
      if (dialogType.value === 'add') {
        try {
          editLoading.value = true
          let res = await AddDriveSchoolList({
            storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
            name: form.name,
            photo: form.photo,
            contactPerson: form.contactPerson,
            contactPhone: form.contactPhone,
            address: form.address,
            onlineStatus: form.onlineStatus,
            activeStatus: form.activeStatus,
            sort: form.sort,
            latitude: form.latitude,
            longitude: form.longitude
          })
          if (res.code === '00000') {
            ElMessage.success(message)
            dialogVisible.value = false
            getData()
          }
        } catch (e) {
        } finally {
          editLoading.value = false
        }
      } else {
        try {
          editLoading.value = true
          const formData = new FormData()
          let obj = {
            id: form.id,
            storeId: parseInt(localStorage.getItem('lty-store-id') || '0'),
            name: form.name,
            photo: form.photo,
            contactPerson: form.contactPerson,
            contactPhone: form.contactPhone,
            address: form.address,
            onlineStatus: form.onlineStatus,
            activeStatus: form.activeStatus,
            sort: form.sort,
            latitude: form.latitude,
            longitude: form.longitude
          }
          Object.keys(obj).forEach((key) => {
            formData.append(key, String(obj[key as keyof typeof obj]))
          })
          let res = await EditDriveSchoolList(obj)
          if (res.code === '00000') {
            ElMessage.success(message)
            dialogVisible.value = false
            getData()
          }
        } catch (e) {
        } finally {
          editLoading.value = false
        }
      }
    }
  })
}

async function editActiveStatus(id: any, status: number) {
  try {
    const res = await EditDriveSchoolList({
      id,
      activeStatus: status
    })
    if (res.code === '0') {
    }
  } catch (e) {
  } finally {
    await getData()
  }
}
async function editOnlineStatus(id: any, status: number) {
  try {
    const res = await EditDriveSchoolList({
      id,
      onlineStatus: status
    })
    if (res.code === '00000') {
    }
  } catch (e) {
  } finally {
    await getData()
  }
}
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const handleClick = (e: any) => {
  console.log(e, 'e===')
  if (e === '1') {
    setTimeout(() => {
      router.push('/drivingschool/DrivingschoolManagement')
    }, 0)
  } else if (e === '2') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type')
    }, 0)
  } else if (e === '3') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_baoming')
    }, 0)
  } else if (e === '4') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_zhaosheng')
    }, 0)
  } else if (e === '5') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_jiaolian')
    }, 0)
  } else if (e === '6') {
    setTimeout(() => {
      router.push('/drivingschool/question_bank_type_xunlianchang')
    }, 0)
  }
}

function selectMapAddress(value: any) {
  form.latitude = value.lat
  form.longitude = value.lng
  showMapDialog.value = false
}

const handleDelImg = () => {
  form.photo = ''
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tableimg {
  width: 8rem;
  height: 4.5rem;
  border-radius: 0.5rem;
  overflow: hidden;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
